package com.thrd.basicframework.utils;

import android.text.TextUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: ${唐杰}
 * @date: 2021/4/6
 */
public class HtmlUtils {
    /**
     * 获取html中的所有图片
     * @param compatText
     * @return
     */
    public static List<String> filterImages(String compatText){
        List<String> uList = new ArrayList<>();
        if(!TextUtils.isEmpty(compatText)&&compatText.contains("<img")){
            //get img src
            Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");//<img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
            Matcher m = p.matcher(compatText);
            String searchAttrib = "src";
            String regxpForTagAttrib = searchAttrib + "\\s*=\\s*[\"|']http://([^\"|']+)[\"|']";//"=[\"|']([^[\"|']]+)[\"|']";
            Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);
            while(m.find()){
                Matcher matcherForAttrib = patternForAttrib.matcher(m.group());
                if (matcherForAttrib.find()) {
                    System.out.println("poe " +"http://" +matcherForAttrib.group(1));
                    uList.add("http://" +matcherForAttrib.group(1));
                }
            }
        }
        return  uList;
    }

    /**
     * 1.向富文本中插入执行函数sayHello
     * 2.修改后的文本插入<html></html> 组合为新的页面 .
     * @param compatText
     */
    public static String constructExecActionJs(String compatText){
        StringBuffer sb = new StringBuffer();
        sb.append("<html> " +
                "<script type=\"text/javascript\"> " +
                "  function showImage(position , url) {\n" +
                "        window.control.showImage(position,url)\n" +
                "    }"+
                "</script>");
        //插入函数
        sb.append(insertExecActionJs(compatText));
        sb.append("</html>");
        return  sb.toString();
    }

    public static String insertExecActionJs(String compatText){
        String searchAttrib = "src";
        String regxpForTag ="<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
        Pattern patternForTag = Pattern.compile(regxpForTag);
        String regxpForTagAttrib = searchAttrib + "\\s*=\\s*[\"|']http://([^\"|']+)[\"|']";//"=[\"|']([^[\"|']]+)[\"|']";
        Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);
        Matcher matcherForTag = patternForTag.matcher(compatText);
        StringBuffer sb = new StringBuffer();
        boolean result = matcherForTag.find();
        int pos = 0 ;
        while (result) {
            StringBuffer sbreplace = new StringBuffer();
            System.out.println(matcherForTag.group());
            Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group());

            if (matcherForAttrib.find()) {
                System.out.println("ll"+matcherForAttrib.group());
                matcherForAttrib.appendReplacement(sbreplace, searchAttrib+"=\"http://"
                        + matcherForAttrib.group(1) +"\""+ " onclick=\"showImage(" +
                        +pos+"," +
                        "'http://" +matcherForAttrib.group(1) +"'"
                        +")\"");
            }
            matcherForAttrib.appendTail(sbreplace);
            matcherForTag.appendReplacement(sb, sbreplace.toString());
            result = matcherForTag.find();
            pos++;
        }
        matcherForTag.appendTail(sb);
        System.out.println("poe: "+sb.toString());
        return  sb.toString();
    }



    public static String getNewContent(String htmltext) {
        //jsoup解析body数据
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            //没有加载css，所以会出现图片很大导致可以左右滑动。这里将所有图片的宽度设为100%，解决这个问题
            element.attr("width", "100%").attr("height", "auto");
            //将src的地址放入alt，可以替换成其他的属性
            //但是注意不能放到自定义的如_src中，会导致js代码中this._src取到undefine
            //我不懂js，所以只能放在原有的属性中
            element.attr("alt", element.attr("src"));
            //将src的值替换为assets文件夹下loading_image_default.png
            element.attr("src", "file:///android_asset/loading_image_default.gif");
            //  element.attr("onerror","file:///android_asset/loading_image_default.png");

            element.attr("onerror","this.src='file:///android_asset/loading_default_net.png'");
        }
        return doc.toString();
    }

}
